<ToggleButton
x:Name="ToogleBtn"
Margin="150 0 0 0"
Width="44"
Height="44">
<ToggleButton.Style>
<Style TargetType="ToggleButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Image x:Name="img" Source="Image/Car-Loan.png" />
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="img" Property="Source" Value="Image/Car-Loan-WF.png" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToggleButton.Style>
</ToggleButton>
但上述的使用方式,若有多個ToggleButton,且每個都不同圖片時,會造成Xaml較長,因此改善其作法
public ImageSource CheckedImageSource
{
get => (ImageSource)GetValue(CheckedImageSourceProperty);
set => SetValue(CheckedImageSourceProperty, value);
}
public static readonly DependencyProperty CheckedImageSourceProperty =
DependencyProperty.Register("CheckedImageSource", typeof(ImageSource), typeof(ImageToggleButton), new PropertyMetadata(null));
public ImageSource UncheckedImageSource
{
get => (ImageSource)GetValue(UncheckedImageSourceProperty);
set => SetValue(UncheckedImageSourceProperty, value);
}
public static readonly DependencyProperty UncheckedImageSourceProperty =
DependencyProperty.Register("UncheckedImageSource", typeof(ImageSource), typeof(ImageToggleButton), new PropertyMetadata(null));
<Style TargetType="{x:Type local:ImageToggleButton}">
<Setter Property="Height" Value="50" />
<Setter Property="Width" Value="50" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ImageToggleButton}">
<Image x:Name="img" Source="{TemplateBinding UncheckedImageSource}" />
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="img" Property="Source" Value="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=CheckedImageSource}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<local:ImageToggleButton CheckedImageSource="Image/Car-Loan.png" UncheckedImageSource="Image/Align-Right.png" />
https://github.com/houzhiwei/WPFImageToggleButton.git